// 广告相关的路由
const express = require("express");
const path = require("path");
let router = express.Router();
const advModel = require("../models/advModel");
//提取到工具类util文件中
// 引入工具类(文件上传)
let { uploadimg } = require("../util");
// const formidable=require("formidable");
// let form = new formidable.IncomingForm({
//     uploadDir:path.resolve(process.cwd(), "./static"),  // 上传文件存储的路径
//     keepExtensions:true   // 保持之前上传文件的后缀名称
// });


router.get("/getdata", async (req, res) => {
  try {
    //分页过滤
    let advData = await advModel.find();
    console.log("访问成功");
    //总数据条数
    let totalCount = advData.length;
    //每页需要显示的条数
    let perpage = 3;
    //页码
    let pageCount = Math.ceil(totalCount / perpage);
    //前端传递给后端的页码 p
    let { p } = req.query;
    let filterData = await advModel.find().skip((p - 1) * perpage).limit(perpage)

    res.json({
      info: "广告信息获取成功",
      status: 1,
      //传入过滤后的数据给前端
      adv: filterData,
      pageCount
    })
  } catch (err) {
    res.json({
      info: "广告信息获取失败",
      status: 0,
      err
    })
  }
})


// addadv添加路由
router.post("/addadv", async (req, res) => {
  //通过formidable模块把提交过来了数据和文件分开返回
  //以提取到工具类中(util)
  // form.parse(req,(err,fields,files)=>{
  //     if(err){
  //         return console.log(err);
  //     }
  //     console.log(fields,files);
  //     let newFilename=files.imgFile.newFilename
  //     console.log([fields],newFilename);
  // })
  let result = await uploadimg(req)
  console.log("500", result);
  try {
    result.time = new Date().toLocaleDateString();
    console.log(result, "1111");
    let resobj = await advModel.create(result);
    console.log(resobj, "999");
    res.json({
      info: "广告添加成功",
      status: 1
    })
  } catch (err) {
    res.json({
      info: "广告添加失败",
      status: 0,
      err
    })
  }

})

//删除路由
router.delete("/deladv", async (req, res) => {
  let { _id } = req.query;
  console.log(_id);
  try {
    let resobj = await advModel.deleteOne({ _id });
    res.json({
      info: "删除成功",
      status: 1,
      resobj
    })
  } catch (err) {
    res.json({
      info: "删除失败",
      status: 0,
      err
    })
  }
})

module.exports = router